package com.lhy.controller;


import com.lhy.common.vo.Result;
import com.lhy.service.LogService;
import com.mongodb.client.gridfs.model.GridFSFile;
import org.apache.tomcat.jni.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class LogController {

    @Resource
    private LogService logService;

    private final String filepathDir = "D:\\graduate_Project\\file\\";

    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        //旧的文件名称
        String oldfilename = file.getOriginalFilename();
        //获取文件扩展名
        String extname = oldfilename.substring(file.getOriginalFilename().lastIndexOf("."));

        //防止重名
        String newfliename = UUID.randomUUID().toString() + extname;
        //返回是整个文件的大小
        String savepath = filepathDir + newfliename;
        File file1 = new File(savepath);
        if(!file1.exists()){
            file1.createNewFile();
        }
        Integer n= FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(new File(savepath)));
        long size = file.getSize();
        if(n!=size){
            return "文件上传失败！";
        }else {
            return savepath;
        }
    }

    @PostMapping("up")
    public String doUpload(@RequestParam("file")MultipartFile file) throws Exception {
        return logService.saveMultipartFile(file);
    }

    @GetMapping("down")
    public Map<String,Object> selectAll()throws Exception{
        return logService.selectAll();
    }

    //查询所有
    @GetMapping("list")
    public Map<String,Object> selectLogList(){
        return logService.selectLogList();
    }

}
